package com.diary.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diary.common.context.BaseContext;
import com.diary.common.result.Result;
import com.diary.server.entity.Des;
import com.diary.server.service.impl.DesServiceImpl;
import com.diary.server.vo.DesVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.List;

@RestController
@Tag(name = "日记描述接口")
@Slf4j
@RequestMapping("/des")
public class DesController {

    @Autowired
    private DesServiceImpl desService;

    private List<DesVO> changeDate(List<Des> diaries) {
        return diaries.stream().map(des -> {
            return DesVO.builder()
                    .id(des.getId())
                    .recordTime(des.getRecordTime())
                    .des(des.getDes())
                    .build();
        }).toList();
    }

    @GetMapping("/weekly")
    @Operation(summary = "获取指定周的日记列表")
    public Result<List<DesVO>> getWeeklyDiaries(
            @RequestParam Long userId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        try {
            // 验证日期格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate start = LocalDate.parse(startDate, formatter);
            LocalDate end = LocalDate.parse(endDate, formatter);

            // 验证日期范围是否合理（应该是一周的范围）
            if (start.isAfter(end) || ChronoUnit.DAYS.between(start, end) > 31) {
                return Result.error("日期范围不合法");
            }

            List<Des> diaries = desService.getWeeklyDiaries(userId, start, end);
            List<DesVO> result = changeDate(diaries);

            log.info("获取周日记列表成功，用户ID: {}, 数量: {}", userId, result.size());
            return Result.success(result);
        } catch (DateTimeParseException e) {
            log.error("日期格式错误: ", e);
            return Result.error("日期格式错误，请使用 yyyy-MM-dd 格式");
        } catch (Exception e) {
            log.error("获取周日记列表失败，用户ID: {}", userId, e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @GetMapping("/updateBydate")
    @Operation(summary = "根据日期更新小记")
    public Result<Des> updateByDate(@RequestParam String recordTime, @RequestParam String des) {


            LocalDate localDate = LocalDate.parse(recordTime);
            Long userId = BaseContext.getCurrentId();
            Des newdes = desService.getOne(new QueryWrapper<Des>()
                    .eq("user_id", userId)
                    .ge("record_time", localDate.atStartOfDay())
                    .lt("record_time", localDate.plusDays(1).atStartOfDay()));

            if (newdes == null) {
//                return Result.error("小记不存在");
                desService.save(Des.builder().userId(userId).recordTime(localDate.toString()).des( des).build());
            }else{
                newdes.setDes(des);
                boolean update = desService.updateById(newdes);
            }
            log.info("更新小记成功，用户ID: {}, 日期: {}", userId, recordTime);
        return Result.success(newdes);
    }

}
